#!/bin/bash

# Setup the variables

OUT_DIR=out
BIN_NAME=B1_FLASH_16M_V1.11.img

UBOOT_FILE_PATH=uboot.bin
APP_FILE_PATH=ipcam.bin.zip
RES_FILE_PATH=res.jffs2
RECOVERY_FILE_PATH=recovery.bin
RESERVED_FILE_PATH=reserved
CONFIG_FILE_PATH=config.jffs2

BLANK_FILE_PATH=blank.bin

UBOOT_OFFSET=0
UBOOT_SIZE_KBYTES=1024
APP_OFFSET=1024
APP_SIZE_KBYTES=7168
RES_OFFSET=8192
RES_SIZE_KBYTES=3072
RECOVERY_OFFSET=11264
RECOVERY_SIZE_KBYTES=3072
RESERVED_OFFSET=14336
RESERVED_SIZE_KBYTES=896
CONFIG_OFFSET=15232
CONFIG_SIZE_KBYTES=1024

BLANK_OFFSET=14336
BLANK_SIZE_KBYTES=2048

FLASH_TOTAL_SIZE=16384


# check root permission
sudo echo
if [ $? -ne 0 ]; then
    echo "please check root permission."
    exit 1
fi

# build step by step


# pack each part
mkdir -p ${OUT_DIR}
tr '\000' '\377' < /dev/zero | dd of=${OUT_DIR}/${BIN_NAME} bs=1K count=${FLASH_TOTAL_SIZE} > /dev/null

dd if=${UBOOT_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${UBOOT_OFFSET}
dd if=${APP_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${APP_OFFSET}
dd if=${RES_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${RES_OFFSET}
dd if=${RECOVERY_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${RECOVERY_OFFSET}
dd if=${BLANK_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${BLANK_OFFSET}
#dd if=${RESERVED_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${RESERVED_OFFSET}
#dd if=${CONFIG_FILE_PATH} of=${OUT_DIR}/${BIN_NAME} bs=1K seek=${CONFIG_OFFSET}

echo "Generate Camera firmware at: "${OUT_DIR}/${BIN_NAME}
